package com.utils

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.MediaStore
import android.util.Base64
import java.io.ByteArrayOutputStream
import java.io.File


class ImageUtils {
    companion object {
        fun convertImageToBase64(imagePath: String?): String? {
            val bitmap = BitmapFactory.decodeFile(imagePath) // 从文件路径加载位图
            val byteArrayOutputStream = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream) // 将位图压缩成字节数组输出流
            val bytes = byteArrayOutputStream.toByteArray() // 获取字节数组
            return Base64.encodeToString(bytes, Base64.DEFAULT) // 将字节数组编码为Base64字符串并返回
        }
        @SuppressLint("Range")
        fun getImageContentUri(context: Context, path: String): Uri? {
            val cursor = context.contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                arrayOf(MediaStore.Images.Media._ID),
                MediaStore.Images.Media.DATA + "=? ",
                arrayOf(path),
                null
            )
            return if (cursor != null && cursor.moveToFirst()) {
                val id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
                val baseUri = Uri.parse("content://media/external/images/media")
                Uri.withAppendedPath(baseUri, "" + id)
            } else {
                // 如果图片不在手机的共享图片数据库，就先把它插入。
                if (File(path).exists()) {
                    val values = ContentValues()
                    values.put(MediaStore.Images.Media.DATA, path)
                    context.contentResolver.insert(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        values
                    )
                } else {
                    null
                }
            }
        }
        fun getBitmapFromUri(context: Context, uri: Uri?): Bitmap? {
            try {
                val parcelFileDescriptor = context.contentResolver.openFileDescriptor(
                    uri!!, "r"
                )
                val fileDescriptor = parcelFileDescriptor!!.fileDescriptor
                val image = BitmapFactory.decodeFileDescriptor(fileDescriptor)
                parcelFileDescriptor.close()
                return image
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return null
        }
    }
}